const strFormat = require("../../util/strFormat");
const sql = (start, length) => {
  return strFormat(
    "select a.licence, a.maxload, a.busload, a.faultcondition, a.runningcondition, a.speed, a.longitude, a.dimensionality, b.lineid, c.name as linename, a.pindex " + 
    "from bus as a " + 
    "left join businline as b " + 
    "on a.licence=b.licence " + 
    "left join line as c " + 
    "on b.lineid=c.id " +
    "limit {start},{length};",
    { start: start, length: length }
  );
};

const getbusinfo = (connection, req, res) => {
  const start = parseInt(req.query.start) || 0;
  const length = parseInt(req.query.length) || 1000;

  connection.query(sql(start, length), (err, result) => {
    var data = null;

    if ( err ) {
      console.error(err);
      res.status(200).json({
        status: "fail",
        data: data,
      });
      return;
    } else {
      data = [];

      result.forEach(item => {
        data.push({
          licence: item.licence,
          maxload: item.maxload,
          busload: item.busload,
          faultcondition: item.faultcondition,
          runningcondition: item.runningcondition,
          speed: item.speed,
          longitude: item.longitude,
          dimensionality: item.dimensionality,
          lineid: item.lineid,
          linename: item.linename,
          pindex: item.pindex,
        });
      });

      res.status(200).json({
        status: "success",
        data: data,
      });
    }
  });
}

module.exports = getbusinfo;